package com.sunsharing.common;

import com.sunsharing.common.utils.StringUtils;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * water的URL样式:protocol://domain.ip:port?byClient=true
 * protocol:mina
 * domain:域名
 * byClient:主动模式，服务端不主动连客户端
 * User: criss
 * Date: 13-4-2
 * Time: 下午7:36
 * To change this template use File | Settings | File Templates.
 */
public class URL {

    String protocol;
    String domain;
    String ip;
    int port;
    String path;
    Map<String,String> parameters;

    public  URL(String protocol,String domain,String ip,int port,String path,Map<String,String>parameters)
    {
        this.protocol = protocol;
        this.domain = domain;
        this.ip = ip;
        this.port = port;
        this.path = path;
        this.parameters = parameters;
    }

    public static URL clone(URL url)
    {
        Map<String,String> par = new HashMap<String, String>();
        par.putAll(url.parameters);
        URL ret = new URL(url.protocol,url.domain,url.ip,url.port,url.path,par);
        return ret;
    }

    public String toString()
    {
        String url = protocol+"://"+domain+"."+ip+":"+port;

        if(parameters.keySet().size()!=0)
        {
             String par = "";
             for(Iterator<String> iter = parameters.keySet().iterator();iter.hasNext();)
             {
                 String key = iter.next();
                 String value = parameters.get(key);
                 par+=key+"="+value+"&";
             }
            par = par.substring(0,par.length()-1);
            return url+"?"+par;
        }else
        {
            return url;
        }
    }
    /**
     * Parse url string
     *
     * @param url URL string
     * @return URL instance
     * @see URL
     */
    public static URL valueOf(String url) {
        if (url == null || (url = url.trim()).length() == 0) {
            throw new IllegalArgumentException("url == null");
        }
        String protocol = null;
        String username = null;
        String password = null;
        String host = null;
        int port = 0;
        String path = null;
        Map<String, String> parameters = new HashMap<String, String>();
        int i = url.indexOf("?"); // seperator between body and parameters
        if (i >= 0) {
            String[] parts = url.substring(i + 1).split("\\&");

            for (String part : parts) {
                part = part.trim();
                if (part.length() > 0) {
                    int j = part.indexOf('=');
                    if (j >= 0) {
                        parameters.put(part.substring(0, j), part.substring(j + 1));
                    } else {
                        parameters.put(part, part);
                    }
                }
            }
            url = url.substring(0, i);
        }
        i = url.indexOf("://");
        if (i >= 0) {
            if(i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\"");
            protocol = url.substring(0, i);
            url = url.substring(i + 3);
        }
        else {
            // case: file:/path/to/file.txt
            i = url.indexOf(":/");
            if(i>=0) {
                if(i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\"");
                protocol = url.substring(0, i);
                url = url.substring(i + 1);
            }
        }

        i = url.indexOf("/");
        if (i >= 0) {
            path = url.substring(i + 1);
            url = url.substring(0, i);
        }
        i = url.indexOf("@");
        if (i >= 0) {
            username = url.substring(0, i);
            int j = username.indexOf(":");
            if (j >= 0) {
                password = username.substring(j + 1);
                username = username.substring(0, j);
            }
            url = url.substring(i + 1);
        }
        i = url.indexOf(":");
        if (i >= 0 && i < url.length() - 1) {
            port = Integer.parseInt(url.substring(i + 1));
            url = url.substring(0, i);
        }
        if(url.length() > 0) host = url;

        i = host.indexOf(".");
        String domain = "";
        if(i==-1)
        {
            domain = "default";
        }else
        {
            domain = host.substring(0, i);
        }
        host = host.substring(i+1);
        return new URL(protocol, domain ,host, port, path, parameters);
    }

    public String getProtocol() {
        return protocol;
    }

    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }

    public String getDomain() {
        return domain;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

//    public Map<String, String> getParameters() {
//        return parameters;
//    }

    public void setParameters(URL url) {
        this.parameters.putAll(url.parameters);
    }

    public String getFromNodeId()
    {
        return parameters.get(Constant.URL_PAR_FROM_NODE_ID);
    }

    public String getToNodeId()
    {
        return parameters.get(Constant.URL_PAR_TO_NODE_ID);
    }


    public String getMyNodeId()
    {
        return parameters.get(Constant.URL_PAR_MY_NODE_ID);
    }

    public String getMailbox()
    {
        String mail = parameters.get(Constant.URL_PAR_MAILBOX);
        if(mail==null)
        {
            return Constant.MAILBOX_MEM;
        }else
        {
            return mail;
        }
    }

    public String getIsClient()
    {
        String isclient = parameters.get(Constant.URL_PAR_ISCLIENT);
        if(isclient==null)
        {
            throw new RuntimeException("URL必须包含isclient");
        }
        return isclient;
    }

    public void putPar(String key,String value)
    {
        parameters.put(key,value);
    }

    public String getChannelName()
    {
        String proName = parameters.get(Constant.URL_PAR_CHANNEL_NAME);
        return proName;
    }
    public String getByClient()
    {
        String byClient = parameters.get(Constant.URL_PAR_BYCLIENT);
        if(byClient==null)
        {
            return "false";
        } else
        {
            return byClient;
        }
    }
    private String getFileChannelPath(String nodeId)
    {
        String rootFilePath = parameters.get(Constant.URL_PAR_ROOT_FILE_PATH);
        if(StringUtils.isBlank(rootFilePath))
        {
            rootFilePath = ".";
        }
        if(!rootFilePath.endsWith("/"))
        {
            rootFilePath +="/";
        }
        File tmp = new File(rootFilePath+nodeId+"/send");
        if(!tmp.exists())
        {
            tmp.mkdirs();
        }
        tmp = new File(rootFilePath+nodeId+"/receive");
        if(!tmp.exists())
        {
            tmp.mkdirs();
        }
        tmp = new File(rootFilePath+nodeId+"/back");
        if(!tmp.exists())
        {
            tmp.mkdirs();
        }
        return rootFilePath+nodeId;
    }

    public String getSendFilePath(String nodeId)
    {
        return getFileChannelPath(nodeId)+"/send";
    }

    public String getReceiveFilePath(String nodeId)
    {
        return getFileChannelPath(nodeId)+"/receive";
    }



}
